import React, { useState, useEffect } from 'react';
import { categoryApi, articleApi } from '../../api/knowledge';
import { Spin, Row, Col, Card, List, Typography, Empty, message } from 'antd';
import './index.css';

const { Title, Text, Paragraph } = Typography;

const KnowledgeBrowser = () => {
  // 状态管理
  const [loading, setLoading] = useState({
    categories: false,
    subcategories: false,
    articles: false
  });
  const [categoryOne, setCategoryOne] = useState([]);
  const [categoryTwo, setCategoryTwo] = useState([]);
  const [articles, setArticles] = useState([]);
  const [selectedCategory, setSelectedCategory] = useState({
    levelOne: null,
    levelTwo: null
  });

  // 获取所有一级分类
  useEffect(() => {
    const fetchCategoryOne = async () => {
      setLoading(prev => ({ ...prev, categories: true }));
      try {
        const data = await categoryApi.getAllLevelOne();
        setCategoryOne(data || []);
        // 如果有分类数据，默认选中第一个
        if (data && data.length > 0) {
          handleCategoryOneClick(data[0]);
        }
      } catch (error) {
        message.error('获取一级分类失败：' + error.message);
      } finally {
        setLoading(prev => ({ ...prev, categories: false }));
      }
    };

    fetchCategoryOne();
  }, []);

  // 处理一级分类点击
  const handleCategoryOneClick = async (category) => {
    setSelectedCategory(prev => ({ ...prev, levelOne: category, levelTwo: null }));
    setArticles([]); // 清空文章列表
    
    setLoading(prev => ({ ...prev, subcategories: true }));
    try {
      const data = await categoryApi.getLevelTwoByParentId(category.id);
      setCategoryTwo(data || []);
      // 如果有二级分类数据，默认选中第一个
      if (data && data.length > 0) {
        handleCategoryTwoClick(data[0]);
      }
    } catch (error) {
      message.error('获取二级分类失败：' + error.message);
    } finally {
      setLoading(prev => ({ ...prev, subcategories: false }));
    }
  };

  // 处理二级分类点击
  const handleCategoryTwoClick = async (category) => {
    setSelectedCategory(prev => ({ ...prev, levelTwo: category }));
    
    setLoading(prev => ({ ...prev, articles: true }));
    try {
      const data = await articleApi.getList({
        categoryOneId: selectedCategory.levelOne.id,
        categoryTwoId: category.id,
        status: 1 // 只获取已发布的文章
      });
      setArticles(data || []);
    } catch (error) {
      message.error('获取文章列表失败：' + error.message);
    } finally {
      setLoading(prev => ({ ...prev, articles: false }));
    }
  };

  // 处理文章点击
  const handleArticleClick = (article) => {
    // 可以跳转到文章详情页
    window.location.href = `/article/${article.id}`;
  };

  return (
    <div className="knowledge-browser-container">
      <Row gutter={16} className="knowledge-browser-row">
        {/* 一级分类列表 */}
        <Col span={4} className="category-col">
          <Card title="知识分类" bordered={false} className="category-card">
            <Spin spinning={loading.categories}>
              <List
                dataSource={categoryOne}
                renderItem={item => (
                  <List.Item
                    className={`category-item ${selectedCategory.levelOne?.id === item.id ? 'category-item-active' : ''}`}
                    onClick={() => handleCategoryOneClick(item)}
                  >
                    {item.icon && <span className="category-icon">{item.icon}</span>}
                    <span>{item.name}</span>
                  </List.Item>
                )}
                locale={{ emptyText: <Empty description="暂无分类" /> }}
              />
            </Spin>
          </Card>
        </Col>

        {/* 二级分类列表 */}
        <Col span={5} className="subcategory-col">
          <Card 
            title={selectedCategory.levelOne ? `${selectedCategory.levelOne.name}的子分类` : "子分类"} 
            bordered={false} 
            className="category-card"
          >
            <Spin spinning={loading.subcategories}>
              <List
                dataSource={categoryTwo}
                renderItem={item => (
                  <List.Item
                    className={`category-item ${selectedCategory.levelTwo?.id === item.id ? 'category-item-active' : ''}`}
                    onClick={() => handleCategoryTwoClick(item)}
                  >
                    {item.icon && <span className="category-icon">{item.icon}</span>}
                    <span>{item.name}</span>
                  </List.Item>
                )}
                locale={{ emptyText: <Empty description="暂无子分类" /> }}
              />
            </Spin>
          </Card>
        </Col>

        {/* 文章列表 */}
        <Col span={15} className="article-col">
          <Card 
            title={
              selectedCategory.levelTwo 
                ? `${selectedCategory.levelOne.name} > ${selectedCategory.levelTwo.name}` 
                : "文章列表"
            } 
            bordered={false} 
            className="article-card"
          >
            <Spin spinning={loading.articles}>
              <List
                itemLayout="vertical"
                dataSource={articles}
                renderItem={item => (
                  <List.Item
                    key={item.id}
                    className="article-item"
                    onClick={() => handleArticleClick(item)}
                  >
                    <div className="article-header">
                      <Title level={4}>{item.title}</Title>
                      <div className="article-meta">
                        <Text type="secondary">浏览: {item.viewCount}</Text>
                        <Text type="secondary" style={{ marginLeft: 16 }}>使用: {item.useCount}</Text>
                        <Text type="secondary" style={{ marginLeft: 16 }}>
                          {new Date(item.createdAt).toLocaleDateString()}
                        </Text>
                      </div>
                    </div>
                    <Paragraph ellipsis={{ rows: 2 }} className="article-summary">
                      {item.summary || '暂无简介'}
                    </Paragraph>
                  </List.Item>
                )}
                locale={{ emptyText: <Empty description="暂无文章" /> }}
              />
            </Spin>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default KnowledgeBrowser;
